/**

This file is part of MaCI/GIMnet.

MaCI/GIMnet is free software: you can redistribute it and/or modify it 
under the terms of the GNU Lesser General Public License as published 
by the Free Software Foundation, either version 3 of the License, or 
(at your option) any later version.

MaCI/GIMnet is distributed in the hope that it will be useful, but WITHOUT 
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 
FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public 
License for more details.

You should have received a copy of the GNU Lesser General Public 
License along with GIMnet. (See COPYING.LESSER) If not, see 
<http://www.gnu.org/licenses/>.

**/
#include "ImageLogger.hpp"
#include "gimutils.h"
// -*- coding:iso-8859-15 mode: c++ -*-
/** 
 * \file
 * \brief MaCI_Image Logger implementation.
 * \author Matthieu Myrsky <matthieu.myrsky@tkk.fi>
 *
 * $Id$
 *
 */


ImageLogger::ImageLogger(MaCI::Image::CImageClient *aClient,
                               std::string aMaCISLName):
  CSync(1, 1),               
  CThread(1),                
  Logger(),
  iIClient(aClient),
  iRunning(false),
  iRunningThreadStopped(true),
  iPathName(),
  iDirectory(),
  iFile(NULL),
  iMaCISLName(aMaCISLName),
  iAdditionalInformation("Not active"),
  iNumberToSkip(0)

{


}



ImageLogger::~ImageLogger(){
  if(iRunning){
    StopLogging();
  }

}

 
bool ImageLogger::StartLogging(void)
{
  dPrint(10,"Start called");
  
  if(!iRunning){
    char buffer[256];
    dPrint(5,"Start logging image events");
        
    gim::time tstamp(true);
    tm t;
    //      MaCI::Common::TTimestamp tstamp;
    tstamp.getLocalTime(t);
    
    sprintf(iPathName,"data/%s_%.2d_%.2d_%d_%.2d:%.2d:%.2d",
            iMaCISLName.c_str(),
            t.tm_mday,
            t.tm_mon+1,
            t.tm_year+1900,
            t.tm_hour,
            t.tm_min,
            t.tm_sec);
    
    sprintf(iDirectory,"%s_%.2d_%.2d_%d_%.2d:%.2d:%.2d",
            iMaCISLName.c_str(),
            t.tm_mday,
            t.tm_mon+1,
            t.tm_year+1900,
            t.tm_hour,
            t.tm_min,
            t.tm_sec);
   
    sprintf(buffer,"data/%s_%.2d_%.2d_%d_%.2d:%.2d:%.2d.txt",
            iMaCISLName.c_str(),
            t.tm_mday,
            t.tm_mon+1,
            t.tm_year+1900,
            t.tm_hour,
            t.tm_min,
            t.tm_sec);
              
    iFile = fopen(buffer,"wt");
    

    mkdir(iPathName,  S_IRWXU);  
    iRunning = true; 
    RunThread(0);
  }

  return false;
}

 
bool ImageLogger::StopLogging(void)
{

  dPrint(10,"stop called");
  if(iRunning){
    Lock();
    iRunning = false;

    Unlock();
    WaitThread(0);

    Lock();
    iAdditionalInformation = "Not active";   
    Unlock();

  }
  return false;
}


int ImageLogger::ThreadFunction(const int aThreadNumber)
{

  using namespace MaCI::Image;
  dPrint(1,"thread %d", aThreadNumber);
  if(aThreadNumber == 0){
    dPrint(1,"thread running");
    CImageData data;
    unsigned int seq = 0;
   
    /////////Search the group and instance names :)
    std::string instance;
    std::string group;

    MaCI::MaCICtrl::SMaCISL sl(iMaCISLName);
    if (sl.IsValidFQMaCISL()) {
      group = sl.GetDeviceGroup();
      instance = sl.GetInstance();
    }
    //////////
        
    fprintf(iFile,"%%MaCI_Image log file\n");
    fprintf(iFile,"%%Group: %s Instance: %s\n",group.c_str(),instance.c_str());

    


    
    int imageStored = 0;
    unsigned int skipped = 0;
    bool first = true;
    EImageDataType format;
    int imageCount = 0;
    while(iRunning){
      char buffer[256];
      char filename[256];
     
      if(iIClient->GetImageData(data,
                                &seq, 
                                5000)){
       
        Lock();
        
        if(first){
          //FIXME: THe data type can be different between images in the same container??
          CImageContainer imageContainer;
          if(data.GetImage(imageContainer)){

            imageCount = data.GetImageCount();
            fprintf(iFile,"%%Path_to_image_files: %s image_count: %d\n",iDirectory,imageCount);
            fprintf(iFile,"%%timestamp_sec timestamp_usec image_count*<imageDataSize imageformat width height>");
            fprintf(iFile,"\n\n\n");
            first = false;            

            //Make directory when multiple images are in one packet for multiple 
            for(int i = 1; i< imageCount; i++){
              char pathBuffer[256];
              sprintf(pathBuffer,"%s/%d",iPathName,i);
              std::string path(pathBuffer);
              dPrint(1,"Creating directory %s",pathBuffer);
              mkdir(pathBuffer,  S_IRWXU);  

            }
          }

        }
        TImageDataIterator imageIteratorPtr = NULL;
        for(int imageIndex = 0; imageIndex < imageCount; imageIndex++){
          FILE *file;
          CImageContainer imageContainer;
          if(skipped >= iNumberToSkip){
            if(data.GetImage(imageContainer,&imageIteratorPtr)){
              format = imageContainer.GetImageDataType();
              
            }else{
              continue;
            }
            const MaCI::Common::TTimestamp *tstamp = data.GetTimestamp();
            if(tstamp){
              //Save only one timestamp to the "log file" used by maci_logger
              if(imageIndex == 0){
                fprintf(iFile,"%.6d %.6d ",tstamp->timestamp_s,tstamp->timestamp_us);
              }

              //Just for support old logged image datasets.... if more than 1 image in
              //container save them in folders named by index (but not the 0)
              if(imageIndex > 0){
                sprintf(buffer,"%s/%d/%.6d_%.6d",
                        iPathName,imageIndex,tstamp->timestamp_s,tstamp->timestamp_us);
              }else{
                sprintf(buffer,"%s/%.6d_%.6d",
                      iPathName,tstamp->timestamp_s,tstamp->timestamp_us);
              }
              
            }else{
              MaCI::Common::TTimestamp tNow;
              if(imageIndex == 0){
                fprintf(iFile,"%.6d %.6d ",tNow.timestamp_s,tNow.timestamp_us);
              }
              if(imageIndex > 0){
                sprintf(buffer,"%s/%d/%.6d_%.6d",
                        iPathName,imageIndex,tNow.timestamp_s,tNow.timestamp_us);
              }else{
                sprintf(buffer,"%s/%.6d_%.6d",
                        iPathName,tNow.timestamp_s,tNow.timestamp_us);

              }
              
            }

            switch(format){

            case KImageDataUnknown:{
            sprintf(filename,"%s.unknown",buffer);
            break;
            }
            case KImageDataJPEG:{
              sprintf(filename,"%s.jpg",buffer);
              break;
            }
            case KImageDataPNG:  {
              sprintf(filename,"%s.png",buffer);
              break;
            }     
            case KImageDataRGB:{
              sprintf(filename,"%s.rgb",buffer);
              break;
            }
            case KImageDataYUV420P:{
              sprintf(filename,"%s.yuv420",buffer);
              break;
            }
            case KImageDataYUV422:{
              sprintf(filename,"%s.yuv422",buffer);
              break;
            }
            case KImageDataGreyscale:{
              sprintf(filename,"%s.gray",buffer);
              break;
            }
            case KImageDataRaw:    {
              sprintf(filename,"%s.raw",buffer);
            break;
            }
            case KImageDataRGBA:{
              sprintf(filename,"%s.rgba",buffer);
              break;
            }
            default:{
              sprintf(filename,"%s.unknown",buffer);
              break;
            }
            }
            
            file = fopen(filename,"wt");          
           
            
            
            
            TImageInfo info = imageContainer.GetImageInfoRef();
            /*              dPrint(1,"storing image to %s... imageCount %d, imageIndex %d",filename,imageCount,imageIndex);
                            dPrint(1,"ptr %p",imageContainer.GetImageDataPtr());
                            dPrint(1,"file ptr %p",file);*/
            //            imageContainer.ConvertTo( KImageDataJPEG);
            
            fwrite(imageContainer.GetImageDataPtr(), imageContainer.GetImageDataSize(), 1, file);
            fprintf(iFile,"%u %u %u %u ",imageContainer.GetImageDataSize(), info.imagedatatype,info.imagewidth,info.imageheight);
            imageStored++;
            skipped = 0;
            if(imageIndex == imageCount -1){
              fprintf(iFile,"\n");
            }
            
            
            fflush(iFile);
            fflush(file);
            fclose(file);
            
            
            sprintf(buffer,"%d image(s) stored to '%s'",imageStored,iPathName);
          
            iAdditionalInformation.clear();
            iAdditionalInformation.assign(buffer);
          }else{
            skipped++;
          }
          
        }
        // dPrint(1,"Waiting image...");
        Unlock();
      }
      
    }
    fclose(iFile);
    Lock();
    iRunningThreadStopped = true;
    Unlock();
    
  }

  return 0;

}

std::string ImageLogger::GetName(){
  return "Image Logger";
}


bool ImageLogger::GetAdditionalInformation(std::string &aInformation){
  Lock();
  aInformation = iAdditionalInformation;
  Unlock();
  return true;
}

bool ImageLogger::SkipNMeasurements(unsigned int aN)
{
  
  Lock();
  iNumberToSkip = aN;
  Unlock();
  return true;

}
